﻿using System;
using System.Text;
using System.Data.Odbc;
using System.Diagnostics;
using System.IO;
using System.Configuration;

namespace QualityRpt
{
	public class DBMJob
	{
		public DBMJob ()
		{
		}
		/// <summary>
		/// 用于装入数据的客户端工具连接符
		/// </summary>
		static OdbcConnectionStringBuilder odbcs = new OdbcConnectionStringBuilder (ConfigurationManager.ConnectionStrings ["CLIENTConn"].ConnectionString);
		/// <summary>
		/// 用于命令的connect to 字符串和reset字符串
		/// </summary>
		static string strconnect = string.Empty;
		static string strreset = string.Empty;
		private static void GetConnect ()
		{
			if (strconnect == string.Empty) {
				//客户端db2命令连接
				object database = "quality";
				object uid = "administrator";
				object pwd = "1";
				odbcs.TryGetValue ("database", out database);
				odbcs.TryGetValue ("uid", out uid);
				odbcs.TryGetValue ("pwd", out pwd);
				strconnect = "db2 connect to " + database.ToString () + " user " + uid.ToString () + " using " + pwd.ToString ();
				strreset = "db2 connect reset";
			}
		}
		public static void RunStat(){
			GetConnect ();//
			string srs1 = "runstats on table rpt.trans_note with distribution and detailed indexes all";
			string srs2 = "runstats on table rpt.trans_lb with distribution and detailed indexes all";
			string srs3 = "runstats on table rpt.trans_tamp with distribution and detailed indexes all";
			string srs4 = "runstats on table rpt.unread_trans_note with distribution and detailed indexes all";
			string srs5 = "runstats on table rpt.obu_card_relation with distribution and detailed indexes all";
			StringBuilder sbRs = new StringBuilder();
			sbRs.AppendLine(strconnect);
			sbRs.AppendLine(srs1); sbRs.AppendLine(srs2); sbRs.AppendLine(srs3);
			sbRs.AppendLine(srs4); sbRs.AppendLine(srs5);
			sbRs.AppendLine(strreset);
			RunDb2Cmd(sbRs.ToString());
		}
		public static void RunStat(string tableName)
		{
			GetConnect ();
			string srs = "runstats on table " + tableName + " with distribution and detailed indexes all";
			StringBuilder sbRs = new StringBuilder();
			sbRs.AppendLine(strconnect);
			sbRs.AppendLine(srs); 
			sbRs.AppendLine(strreset);
			RunDb2Cmd(sbRs.ToString());
		}
		/// <summary>
		/// load query 如果一个表装入暂挂的话，使用该命令解除暂挂状态
		/// </summary>
		/// <returns>The query.</returns>
		/// <param name="tableName">Table name.</param>
		public static int LoadQuery (string tableName)
		{
			GetConnect ();
			int log_type = 0;
			string emptyFile = Environment.CurrentDirectory + "\\empty.txt";
			if (!File.Exists (emptyFile)) {
				File.WriteAllText (emptyFile, string.Empty);
			}
			StringBuilder sbbat = new StringBuilder ();
			sbbat.Clear ();
			string strquery = "db2 load query table " + tableName;
			string strterminate = "db2 load client from " + emptyFile + " of ixf terminate into " + tableName;
			sbbat.AppendLine (strconnect);
			sbbat.AppendLine (strquery);
			sbbat.AppendLine (strreset);
			string rt = RunDb2Cmd (sbbat.ToString ());
			int startIndex = rt.IndexOf ("load query table");
			int endIndex = rt.IndexOf ("connect reset");
			if (startIndex > 0 && endIndex > 0) {
				string strtablestatus = rt.Substring (startIndex, endIndex - startIndex);

				//判断是否load暂挂
				if (strtablestatus.Contains ("装入暂挂")) {//装入失败
					log_type = 2;//错误
					//解除表的暂挂状态
					sbbat.Clear ();
					sbbat.AppendLine (strconnect);
					sbbat.AppendLine (strterminate);
					sbbat.AppendLine (strreset);
					RunDb2Cmd (sbbat.ToString ());
				} 
			}
			return log_type;
		}
		private static string RunDb2Cmd (string batsql)
		{
			sbOutData = new StringBuilder ();
			String batPath = Environment.CurrentDirectory + "\\" + DateTime.Now.Ticks + ".bat";
			File.WriteAllText (batPath, batsql);
			Process process = new Process ();
			process.StartInfo.FileName = "db2cmd.exe";
			process.StartInfo.Arguments = "/i " + batPath;
			process.StartInfo.UseShellExecute = false;          //不使用系统外壳程序启动  
			process.StartInfo.RedirectStandardInput = false;     //重定向输入（一定是true） 
			process.StartInfo.RedirectStandardOutput = true;    //重定向输出  
			process.StartInfo.RedirectStandardError = true;
			process.StartInfo.CreateNoWindow = false;            //不创建窗口 
			process.OutputDataReceived += new DataReceivedEventHandler (process_OutputDataReceived);
			process.ErrorDataReceived += new DataReceivedEventHandler (process_ErrorDataReceived);
			process.Start ();
			process.BeginOutputReadLine ();
			process.BeginErrorReadLine ();
			process.WaitForExit ();
			process.Close ();
			File.Delete (batPath);
			return sbOutData.ToString ();
		}

		static StringBuilder sbOutErr = new StringBuilder ();
		static StringBuilder sbOutData = new StringBuilder ();

		static void process_ErrorDataReceived (object sender, DataReceivedEventArgs e)
		{
			sbOutErr.AppendLine (e.Data);
		}

		static void process_OutputDataReceived (object sender, DataReceivedEventArgs e)
		{
			sbOutData.AppendLine (e.Data);
		}
	}
}

